<?php
/**
 * 用户信息操作类
 * @author:zhulin
 * @since:2012 5.7
 * 
 */
class User_Info{
    
    const TABLE_NAME = 'user_base';
    const TABLE_NAME_SEARCH = 'user_extend';
    
    protected $uId;

    protected $_data;
    protected $_redisInstance;
    /**
     * 缓存的命名空间
     */
    const CACHE_NS = '_userInfo';
    
    const DEVICE_TYPE_IOS = 1;
    
    const DEVICE_TYPE_ANDROID = 2;
    /**
     *单例对象
     */    
    public static $singletonObjects = array();

    /**
	 * 构造器
     *
     * @param int $uId
	 */
	protected function __construct( $uId )
	{
        $this->uId = $uId;
        $this->_cacheKey = $uId . self::CACHE_NS;
        $this->_cacheInstance = Common::getCache();
        $this->_data = $this->_cacheInstance->get( $this->_cacheKey );
        $this->_redisInstance = $this->_getRedis();
        if( $this->_data === false )
        {
            $this->_loadFromDb();
            $this->_saveToCache();
        }

        if( empty( $this->_data ) )
        {
            $this->_data = array();
        }
	}

    public static function getInstance( $uId )
	{
		$className = __CLASS__;
		if( !isset( self::$singletonObjects[$uId][$className] ) )
		{
			self::$singletonObjects[$uId][$className] = new self( $uId );
		}

		return self::$singletonObjects[$uId][$className];
	}
     /*
     * 获取redis实例
     */

    public function _getRedis() {
//        $config = array ('current'=>'127.0.0.1' , 'old' =>'6380') ;
//        $redis = new Helper_Redis($config);
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6380);
        return $redis;
    }
    /**
     *根据用户id 获得用户信息
     * @param type $uid 
     */
    public static  function getUserInfoByUId( $uid){
        $userInfo = Common::getMysql()->getMultiList( self::TABLE_NAME , 'UId' , $uid);
        return $userInfo;
    }
    /**
     * 根据用户名用户密码获取用户信息
     * @param type $Uname   用户名
     * @return type 
     */
    
    public static function getUserInfo( $username,$password)
    {
        if( $username == ''|| $password == '' )
        {
            throw new AppException( 303 );
        }
                $replace = array(
            '[' => '/[',
            ']' => '/]',
            '%' => '/%',
            '_' => '/_',
        );
        $Uname = strtr( $username , $replace);
        $Password = strtr($password , $replace);
        $userInfo = Common::getMysql()->get( self::TABLE_NAME , array( 'UName' => $username , 'UPasswd' => $password ) );
        return $userInfo;
    } 
    
    /**
     * 用户注册
     * @param type $name
     * @param type $passwd
     * 
     */
    
    public static function userRegister($username, $passwd )
    {
        //参数校验
        if( empty( $username ) || empty( $passwd ) )
        {
             throw new AppException( 303 );
        }
        //验证用户是否已被注册
        if( self::userIsExists( $username ) ){
            echo "用户已被注册";
            return false;
           // throw new AppException( 303  );
        }
        //密码长度验证
          $passwd = Helper_Validate::passwordCheck( $passwd );

         //加密密码
        $key = Common::getConfig( 'passEncrypt' );
        $passwdHash = Helper_String::password_hash( $passwd , $key );
         
      

         //用户初始信息
        $userInfo = array(
            'UId'      => Counter_Builder::getInstance()->getUniqueIdByKey( 'UId' ) ,
            'UName'    => $username ,
            'UPasswd'   => $passwdHash 
        );
         
        //添加用户信息到数据库
        $affectedRows = Common::getMysql()->add( self::TABLE_NAME ,$userInfo );
        if( $affectedRows < 1 )
        {
            throw new AppException( 1000 );
        }
        //返回用户信息
        return $userInfo;
    }
    /**
     *高级用户注册
     * @param type $username
     * @param type $passwd
     * @return type 
     */
    public static function userPowerRegister(  $qq, $birth, $sex, $mobile, $email)
    {
        //参数校验
        if( empty( $qq ) || empty ( $birth ) || empty ( $sex )|| empty ( $mobile )|| empty ( $email )  )
        {
           // echo "不能为空";
            throw new AppException( 303 );
        }
         //邮箱验证
        
        $email = Helper_Validate::emailCheck( $email );
       
        //检验邮箱是否已经被注册
        if( self::emailIsExists( $email ) )
        {   
            throw new AppException( 2000 , $email );
        }
       
        //用户初始信息
        $userInfo = array(
            'UNameId'  => $_SESSION['UId'] ,
            'QQ'       => $qq ,
            'Birth'    => $birth ,
            'Sex'      => $sex,
            'Mobile'   => $mobile,
            'Email'    => $email   
        );
       
        //添加用户信息到数据库
        $affectedRows = Common::getMysql()->add( self::TABLE_NAME_SEARCH ,$userInfo );
        if( $affectedRows < 1 )
        {
            
            throw new AppException( 1000 );
        }
        //返回用户信息
        return $userInfo;
    }
    /**
     * 判断用户设置的邮箱是否存在
     *
     * @param string    $email
     * @return  boolean
     */
    public static function emailIsExists( $email ){
        if( empty( $email ) ) {
            throw new AppException( 303 );
        }
        //邮箱地址过滤
       $email = Helper_Validate::emailCheck( $email );

        //根据邮箱查找用户
        $count = Common::getMysql()->getCount( self::TABLE_NAME_SEARCH , array( 'Email' => $email ) );
        return $count ? true : false;
    }
    /**
     * 验证用户名是否存在
     * @param type $Uname
     * @return bool 
     * 
     */
    public static function userIsExists($Uname){
        if( empty( $Uname ) ){
            
            throw new AppException( 303 );
        }
        $count = Common::getMysql()->getCount( self::TABLE_NAME_SEARCH , array( 'UName' =>$Uname ) );
        
        return $count ? true : false;
        
    }
/**
     * 获取用户基本信息
     * @param boolean $includePwd               是否包含密码信息
     * @return array
     */
    public function getInfo()
    {
    
        echo $this->_data;
        return $this->_data;
    }
    /**
     * 从数据库加载用户的基本信息
     * @return array
     */
    private function _loadFromDb()
    {
        //获取用户基本信息
		$userInfo = Indexer::getInstance( $this->uId )->getDb()->get( self::TABLE_NAME , array( 'uId' => $this->uId ) );

        if( $userInfo == false )
        {
            throw new AppException( 5 );
        }
        
        $this->_data = self::formatLngLat( $userInfo );
    }
 /**
     * 返回筛选出的用户
     * @return 
     * array(
     *      userID => userID
     *      )getScreening
     */
    public function getScreening( $dimensions ) {
        
        $allUserRedis = $this->_cacheInstance->hgetall(self::REDIS_NAME);
        $array = array();
        foreach ($allUserRedis as $key => $value) {
            $value = json_decode($value,true);
            $array[$key] = $value;
        } 
        
      //  print_r($array);
        
        $userRedis = array();
        
        foreach ($dimensions as $key => $value) {
            if ( $key == 'PBrand' ) {
                foreach ($array as $key1 => $value1) {
                    if ( !empty ($value1[$key]) && array_key_exists($value, $value1[$key]) ) {
                        $userRedis['PBrand'][] = $key1;
                    }
                }
                if ( empty($userRedis['PBrand']) ) {
                    $userRedis['PBrand'][] = -1;
                }
            }
            if ( $key == 'BCat' ) {
                foreach ($array as $key1 => $value1) {
                    if ( !empty ($value1[$key]) && array_key_exists($value, $value1[$key]) ) {
                        $userRedis['BCat'][] = $key1;
                    }
                }
                if ( empty($userRedis['BCat']) ) {
                    $userRedis['BCat'][] = -1;
                }
            }
            if ( $key == 'SCat' ) {
                foreach ($array as $key1 => $value1) {
                    if ( !empty ($value1[$key]) && array_key_exists($value, $value1[$key]) ) {
                        $userRedis['SCat'][] = $key1;
                    }
                }
                if ( empty($userRedis['SCat']) ) {
                    $userRedis['SCat'][] = -1;
                }
            }
            
            
            
            if ( $key == 'level' ) {
                foreach ($array as $key1 => $value1) {
                    if ( array_key_exists($key, $value1) ) {
                        $userRedis['level'][] = $key1;
                    }
                }
                if ( empty($userRedis['level']) ) {
                    $userRedis['level'][] = -1;
                }
            }

            if ( $key == 'age' ) {
                foreach ($array as $key1 => $value1) {
                    if ( array_key_exists($key, $value1) ) {
                        $userRedis['age'][] = $key1;
                    }
                }
                if ( empty($userRedis['age']) ) {
                    $userRedis['age'][] = -1;
                }
            }

            if ( $key == 'sex' ) {
                foreach ($array as $key1 => $value1) {
                    if ( array_key_exists($key, $value1) ) {
                        $userRedis['sex'][] = $key1;
                    }
                }
                if ( empty($userRedis['sex']) ) {
                    $userRedis['sex'][] = -1;
                }
            }

        }
        
        $val = array_slice($userRedis, 0,1);
        
        foreach ($val as $key => $value) {
            $val = $value;
        }
        
        foreach ($userRedis as $key => $value) {
            $true = array_search(-1,$value);
            if ( is_numeric($true) ){
                return false;
            }
            else {
                $val = array_intersect($value,$val);
            }
        }
        return $val;
    }
    


    
}